package com.woniu;


import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.woniu.enums.ResultCode;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统一异常处理
 * 1、@RestControllerAdvice 全局异常处理
 *     @ExceptionHandler  处理指定的异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<String> handleBusinessException(BusinessException e){
        e.printStackTrace();
        return Result.fail(e.getMessage());
    }

    /**
     * 状态参数异常
     * @param e
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<String> handleParametersException(IllegalArgumentException e){
        e.printStackTrace();
        return Result.fail(e.getMessage());
    }

    /**
     * 最大的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e){
        e.printStackTrace();
        return Result.fail(e.getMessage());
    }

    /**
     * 方法的参数不支持的异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Map<String,String>> handleParametersException(MethodArgumentNotValidException e){

        //拿到错误信息
        List<FieldError> list = e.getBindingResult().getFieldErrors();

        //把错误信息转成map
        Map<String, String> map = list.stream().collect(
                Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));

        e.printStackTrace();

        //返回结果
        return Result.fail(ResultCode.PARAM_IS_BLANK.getMessage(), map);
    }

    @ExceptionHandler(TencentCloudSDKException.class)
    public Result<String> handleTencentCloudSDKException(Exception e){
        e.printStackTrace();
        return Result.fail(e.getMessage());
    }

}
